<template>
  <div class="quiz-page">
    <div class="quiz-container">
      <a-card v-if="loading" class="loading-card">
        <a-spin size="large" />
      </a-card>
      <template v-else>
        <a-card v-if="hasParticipated" class="quiz-record-card">
          <div class="answers-comparison">
            <div class="answer-row">
              <span class="label">正确答案：</span>
              <span class="answer-sequence correct">
                {{ questions.map((q) => q.correctAnswer).join("") }}
              </span>
            </div>
            <div class="answer-row">
              <span class="label">您的答案：</span>
              <span class="answer-sequence">
                {{ questions.map((q) => q.userAnswer).join("") }}
              </span>
            </div>
          </div>
          <div class="wrong-questions" v-if="wrongQuestions.length > 0">
            <h4>错题提示：</h4>
            <div class="wrong-list">
              <span
                v-for="(question, index) in wrongQuestions"
                :key="index"
                class="wrong-item"
              >
                第{{ question.index + 1 }}题
              </span>
            </div>
          </div>
        </a-card>

        <a-card class="quiz-header">
          <div class="quiz-progress">
            <span>题目进度: {{ currentIndex + 1 }}/{{ questions.length }}</span>
            <a-progress
              :percent="((currentIndex + 1) / questions.length) * 100"
            />
          </div>
          <div class="quiz-timer" v-if="!hasParticipated && timeLeft > 0">
            <span>剩余时间: {{ formatTime(timeLeft) }}</span>
          </div>
        </a-card>

        <a-card class="quiz-content" v-if="currentQuestion">
          <h2>{{ currentQuestion.questionContent }}</h2>

          <div class="options-list">
            <div
              v-for="option in questionOptions"
              :key="option.value"
              class="option-item"
              :class="{
                'option-correct':
                  hasParticipated &&
                  option.value === currentQuestion.correctAnswer,
                'option-wrong':
                  hasParticipated &&
                  option.value === currentQuestion.userAnswer &&
                  option.value !== currentQuestion.correctAnswer,
                'option-selected':
                  !hasParticipated &&
                  userAnswers[currentIndex] === option.value,
              }"
              @click="!hasParticipated && selectAnswer(option.value)"
            >
              <span class="option-label">{{ option.value }}.</span>
              {{ option.label }}
              <span
                v-if="
                  hasParticipated &&
                  option.value === currentQuestion.correctAnswer
                "
                class="option-icon correct"
              >
                <check-outlined />
              </span>
              <span
                v-if="
                  hasParticipated &&
                  option.value === currentQuestion.userAnswer &&
                  option.value !== currentQuestion.correctAnswer
                "
                class="option-icon wrong"
              >
                <close-outlined />
              </span>
            </div>
          </div>

          <div class="quiz-actions">
            <a-button v-if="currentIndex > 0" @click="previousQuestion">
              上一题
            </a-button>
            <a-button
              v-if="!hasParticipated"
              type="primary"
              @click="nextQuestion"
              :disabled="!userAnswers[currentIndex]"
            >
              {{ isLastQuestion ? "提交答案" : "下一题" }}
            </a-button>
            <a-button
              v-else
              type="primary"
              @click="nextQuestion"
              v-show="!isLastQuestion"
            >
              下一题
            </a-button>
          </div>
        </a-card>
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, onUnmounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { message } from "ant-design-vue";
import { CheckOutlined, CloseOutlined } from "@ant-design/icons-vue";
import {
  getChallengeQuestionsUsingGet,
  submitAnswersUsingPost,
} from "@/api/activityQuestionController";

interface QuizQuestion {
  id: string;
  questionContent: string;
  optionA: string;
  optionB: string;
  optionC: string;
  optionD: string;
  correctAnswer: string | null;
  userAnswer: string | null;
}

interface QuizData {
  questions: QuizQuestion[];
  hasParticipated: number;
  quizRecord?: {
    totalScore: number;
    correctCount: number;
    answers: string;
  };
}

interface BaseResponse<T> {
  code: number;
  data: T;
  message: string;
}

const route = useRoute();
const router = useRouter();
const loading = ref(true);
const questions = ref<QuizQuestion[]>([]);
const currentIndex = ref(0);
const userAnswers = ref<string[]>([]);
const timeLeft = ref(1800); // 30分钟答题时间
const hasParticipated = ref(false);
let timer: number;

const currentQuestion = computed(() => questions.value[currentIndex.value]);
const isLastQuestion = computed(
  () => currentIndex.value === questions.value.length - 1
);

const questionOptions = computed(() => {
  if (!currentQuestion.value) return [];
  return [
    { label: currentQuestion.value.optionA, value: "A" },
    { label: currentQuestion.value.optionB, value: "B" },
    { label: currentQuestion.value.optionC, value: "C" },
    { label: currentQuestion.value.optionD, value: "D" },
  ].filter((option) => option.label);
});

const formatTime = (seconds: number) => {
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`;
};

const startTimer = () => {
  timer = window.setInterval(() => {
    if (timeLeft.value > 0) {
      timeLeft.value--;
    } else {
      clearInterval(timer);
      submitAnswers();
    }
  }, 1000);
};

const wrongQuestions = computed(() => {
  if (!hasParticipated.value) return [];
  return questions.value
    .map((question, index) => ({
      question,
      index,
    }))
    .filter((item) => item.question.userAnswer !== item.question.correctAnswer);
});

const quizRecord = ref<QuizData["quizRecord"]>();

const loadQuestions = async () => {
  try {
    const challengeId = Number(route.params.id);
    const response = await getChallengeQuestionsUsingGet({ challengeId });
    const apiResponse = response.data as unknown as BaseResponse<QuizData>;
    if (apiResponse?.code === 0 && apiResponse.data) {
      questions.value = apiResponse.data.questions;
      hasParticipated.value = apiResponse.data.hasParticipated === 1;
      if (hasParticipated.value && apiResponse.data.quizRecord) {
        quizRecord.value = apiResponse.data.quizRecord;
      }
      userAnswers.value = new Array(questions.value.length).fill("");
      loading.value = false;
      if (!hasParticipated.value) {
        startTimer();
      }
    }
  } catch (error) {
    message.error("获取题目失败");
    router.push("/activity/quiz-competition");
  }
};

const selectAnswer = (answer: string) => {
  userAnswers.value[currentIndex.value] = answer;
};

const previousQuestion = () => {
  if (currentIndex.value > 0) {
    currentIndex.value--;
  }
};

const nextQuestion = () => {
  if (isLastQuestion.value && !hasParticipated.value) {
    submitAnswers();
  } else if (currentIndex.value < questions.value.length - 1) {
    currentIndex.value++;
  }
};

const submitAnswers = async () => {
  try {
    const challengeId = Number(route.params.id);
    const submitData = {
      challengeId,
      answers: questions.value.map((question: QuizQuestion, index: number) => ({
        questionId: Number(question.id),
        answer: userAnswers.value[index],
      })),
    };
    await submitAnswersUsingPost(submitData);
    message.success("提交成功！");
    router.push("/activity/quiz-competition");
  } catch (error) {
    console.error(error);
    message.error("提交答案失败");
  }
};

onMounted(() => {
  loadQuestions();
});

onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
  }
});
</script>

<style scoped>
.quiz-page {
  min-height: 100vh;
  width: 100%;
  background: url("@/assets/background/ansque.png") no-repeat center top;
  background-size: 100% auto;
  padding: 40px 0;
  position: relative;
}

.quiz-container {
  position: relative;
  max-width: 760px;
  width: 90%;
  margin: 0 auto;
  z-index: 1;
  transform: scale(0.95);
  transform-origin: top center;
}

.loading-card {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
  background: rgba(255, 255, 255, 0.85);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.quiz-header {
  margin-bottom: 20px;
  background: rgba(255, 255, 255, 0.85);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.quiz-progress {
  margin-bottom: 20px;
}

.quiz-timer {
  font-size: 18px;
  color: #1890ff;
  text-align: right;
}

.quiz-content {
  padding: 24px;
  background: rgba(255, 255, 255, 0.85);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.quiz-content h2 {
  margin-bottom: 24px;
  color: #1f1f1f;
  font-size: 18px;
  line-height: 1.6;
}

.options-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin: 24px 0;
}

.option-item {
  position: relative;
  margin-right: 0;
  padding: 16px;
  border: 1px solid #d9d9d9;
  border-radius: 8px;
  transition: all 0.3s;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.option-item:not(.option-correct):not(.option-wrong):hover {
  border-color: #1890ff;
  background-color: #f0f9ff;
}

.option-label {
  font-weight: bold;
  margin-right: 12px;
  color: #666;
}

.option-selected {
  border-color: #1890ff;
  background-color: #e6f7ff;
}

.option-correct {
  border-color: #52c41a;
  background-color: #f6ffed;
}

.option-wrong {
  border-color: #ff4d4f;
  background-color: #fff1f0;
}

.option-icon {
  position: absolute;
  right: 16px;
  font-size: 16px;
}

.option-icon.correct {
  color: #52c41a;
}

.option-icon.wrong {
  color: #ff4d4f;
}

.quiz-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 24px;
}

.quiz-record-card {
  margin-bottom: 20px;
  background: rgba(255, 251, 246, 0.9);
  border: 1px solid #ffd591;
  padding: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.answers-comparison {
  margin-bottom: 16px;
}

.answer-row {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.answer-row .label {
  min-width: 80px;
  color: #873800;
}

.answer-sequence {
  font-family: monospace;
  font-size: 16px;
  letter-spacing: 2px;
  color: #d4380d;
  background: #fff7e6;
  padding: 4px 12px;
  border-radius: 4px;
}

.answer-sequence.correct {
  color: #52c41a;
  background: #f6ffed;
}

.wrong-questions {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px dashed #ffd591;
}

.wrong-questions h4 {
  color: #873800;
  margin-bottom: 12px;
  font-size: 16px;
}

.wrong-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.wrong-item {
  padding: 4px 12px;
  background: #fff2e8;
  border: 1px solid #ffbb96;
  border-radius: 12px;
  color: #d4380d;
  font-size: 14px;
}

@media (max-width: 576px) {
  .quiz-page {
    padding: 20px 0;
  }

  .quiz-container {
    width: 92%;
  }

  .quiz-content h2 {
    font-size: 16px;
  }

  .option-item {
    padding: 12px;
  }

  .answer-row {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .answer-row .label {
    min-width: auto;
  }
}
</style>
